import axios, {
  type AxiosInstance,
  type AxiosResponse,
  type InternalAxiosRequestConfig,
} from "axios";
import { useRouter, useRoute } from "vue-router";
import { PageEnum } from "@/enums/pageEnum";
import { ResponseData } from "./types";
import { checkStatus } from "./checkStatus";
import { handleResponseCode } from "./responseCode";
import { storage } from "@/utils/storage";
import { ACCESS_TOKEN } from "@/store/mutation-type";

declare module "axios" {
  interface AxiosInstance {
    <T = any>(config: AxiosRequestConfig): Promise<ResponseData<T>>;
    <T = any>(
      url: string,
      config?: AxiosRequestConfig,
    ): Promise<ResponseData<T>>;
  }
}
let isRequesting = false;
const router = useRouter();
const route = useRoute();
const { BASE_LOGIN } = PageEnum;

// 创建 axios 实例
const request: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
});

// 请求拦截器
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    if (isRequesting) {
      return Promise.reject(new Error("有请求正在进行中，请稍后再试"));
    }
    isRequesting = true;
    // 添加 token
    const token = storage.get(ACCESS_TOKEN);
    if (token) {
      config.headers.Authorization = `${token}`;
    }
    return config;
  },
  (error) => {
    isRequesting = false;
    return Promise.reject(error);
  },
);

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    isRequesting = false;
    const result = handleResponseCode(response.data);
    if (!result.success) {
      // return Promise.reject(new Error(result.msg));
      return
    }
    return response.data as any;
  },
  (error) => {
    isRequesting = false;
    console.log(`error`, error);
    checkStatus(error.response.status, error.response.data.message);
  },
);

export default request;
